package com.tc.itfarm.api.util;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.applet.Main;

import java.io.Serializable;
import java.util.List;

/**
 * Created by wangdongdong on 2016/8/21.
 */
public class StringUtil {

    private static Logger logger = LoggerFactory.getLogger(StringUtil.class);

    /**
     * 字符串分割成字符串集合
     * @param str
     * @param regex
     * @return
     */
    public static List<String> strToList(String str, String regex) {
        return strToList(str, regex, String.class);
    }

    /**
     * 字符串分割成整数集合
     * @param str
     * @param regex
     * @return
     */
    public static List<Integer> strToNumberList(String str, String regex) {
        return strToList(str, regex, Integer.class);
    }

    /**
     * 字符串分割成集合
     * @param str
     * @param regex
     * @param clazz
     * @param <T>
     * @return
     */
    private static <T> List<T> strToList(String str, String regex, Class<T> clazz) {
        List<T> list = Lists.newArrayList();
        if (StringUtils.isBlank(str) || StringUtils.isBlank(regex)) {
            logger.error("字符串或分割符不能为空!");
            throw new RuntimeException("字符串或分割符不能为空!");
        }
        String[] strs = str.split(regex);
        for (String s : strs) {
            list.add(strToObject(s, clazz));
        }
        return list;
    }

    /**
     * 字符串转为指定类型
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    private static <T> T strToObject(String str, Class<T> clazz) {
        if (clazz.equals(String.class)) {
            return (T) str;
        }
        if (clazz.equals(Integer.class)) {
            return (T) Integer.valueOf(str);
        }
        if (clazz.equals(Float.class)) {
            return (T) Float.valueOf(str);
        }
        if (clazz.equals(Double.class)) {
            return (T) Double.valueOf(str);
        }
        if (clazz.equals(Character.class)) {
            if (str.length() > 1) {
                throw new RuntimeException("illegal argument");
            }
            return (T) Character.valueOf(str.charAt(0));
        }
        if (clazz.equals(Float.class)) {
            return (T) Float.valueOf(str);
        }
        return (T) str;
    }

    /**
     * int数组转成字符串
     * @param array
     *          数组
     * @param split
     *          分隔符
     * @return
     */
    public static String intArraysToStr(Integer [] array, String split) {
        if (array.length < 1) {
            return StringUtils.EMPTY;
        }
        StringBuilder sb = new StringBuilder();
        for (Integer i : array) {
            sb.append(i).append(split);
        }
        return sb.deleteCharAt(sb.lastIndexOf(split)).toString();
    }

}
